import axios from 'axios';
import type { HistoryPayload, RealtimePayload, SensorReading } from '../types';

const BASE_URL = import.meta.env.VITE_API_BASE || '/api';

let useMock = localStorage.getItem('useMock') === '1';
window.addEventListener('qingyu:mock-toggle', (e: Event) => {
  const detail = (e as CustomEvent<boolean>).detail;
  useMock = !!detail;
});

type Scenario = 'auto' | 'low' | 'mid' | 'high';
let mockScenario: Scenario = (localStorage.getItem('mockScenario') as Scenario) || 'auto';
window.addEventListener('qingyu:mock-scenario', (e: Event) => {
  mockScenario = (e as CustomEvent<Scenario>).detail;
});

export async function fetchRealtime(): Promise<RealtimePayload> {
  if (useMock) return mockRealtime();
  const { data } = await axios.get<RealtimePayload>(`${BASE_URL}/realtime`);
  return data;
}

export async function fetchHistory(params?: { from?: number; to?: number; limit?: number }): Promise<HistoryPayload> {
  if (useMock) return mockHistory();
  const { data } = await axios.get<HistoryPayload>(`${BASE_URL}/history`, { params });
  return data;
}

function rand(min: number, max: number) { return Math.random() * (max - min) + min; }

function sampleTurbidityByScenario(): number {
  const s = mockScenario;
  if (s === 'low') return rand(15, 28);
  if (s === 'mid') return rand(35, 70);
  if (s === 'high') return rand(85, 120);
  // auto: 混合三段，形成更自然的波动
  const r = Math.random();
  if (r < 0.33) return rand(15, 28);
  if (r < 0.66) return rand(35, 70);
  return rand(85, 120);
}

function buildReading(base?: Partial<SensorReading>): SensorReading {
  const turbidity = Math.round(sampleTurbidityByScenario());
  // 使用缓动噪声让曲线更平滑
  const noise = () => (Math.random() - 0.5) * 0.1;
  let pumpPct = 1.0; let valvePct = 1.0; let hz = 50; let rpm = 3000;
  if (turbidity < 30) { pumpPct = 0.4 + noise(); valvePct = 0.5 + noise(); hz = rand(25, 30); rpm = rand(1200, 1500); }
  else if (turbidity <= 80) { pumpPct = 0.8 + noise(); valvePct = 0.7 + noise(); hz = rand(35, 40); rpm = rand(1800, 2000); }
  else { pumpPct = 1.0 + noise(); valvePct = 1.0 + noise(); hz = rand(45, 50); rpm = rand(2400, 3000); }
  const flow = turbidity < 30 ? rand(200, 260) : turbidity <= 80 ? rand(160, 220) : rand(120, 180);
  const pressure = turbidity < 30 ? rand(150, 200) : turbidity <= 80 ? rand(140, 190) : rand(130, 180);
  return {
    timestamp: Date.now(),
    turbidityNTU: turbidity,
    flowLMin: Math.round(flow),
    pressureKPa: Math.round(pressure),
    pumpRpm: Math.round(rpm),
    inverterHz: Math.round(hz),
    valveOpenPct: Math.max(0, Math.min(100, Math.round(valvePct * 100))),
    status: 'normal',
    ...base,
  };
}

async function mockRealtime(): Promise<RealtimePayload> {
  return { reading: buildReading() };
}

async function mockHistory(): Promise<HistoryPayload> {
  const now = Date.now();
  const length = 180; // 3小时，以分钟计
  let last = sampleTurbidityByScenario();
  const readings: SensorReading[] = Array.from({ length }).map((_, i) => {
    // 使用随机游走，让曲线自然且平滑
    last += (Math.random() - 0.5) * 2;
    const t = Math.max(10, Math.min(130, last));
    return buildReading({ timestamp: now - (length - i) * 60000, turbidityNTU: Math.round(t) });
  });
  return { readings };
}


